

#import "NSString+computerSize.h"
#import <CommonCrypto/CommonDigest.h>
#include <zlib.h>
#include <CommonCrypto/CommonCrypto.h>

@implementation NSString (computerSize)

- (CGSize)boundingRectWithSize:(CGSize)size
                  withTextFont:(UIFont *)font
{
    if ([self isEqualToString:@""]) {
        return CGSizeMake(0, 0);
    }
    NSMutableParagraphStyle *paragraphStyle = [[NSMutableParagraphStyle alloc] init];
    paragraphStyle.lineBreakMode = NSLineBreakByWordWrapping;
    NSDictionary *attributes = @{NSFontAttributeName:font, NSParagraphStyleAttributeName:paragraphStyle.copy};
    __block CGSize size1;
    WeakSelf;
    dispatch_queue_t queue = dispatch_queue_create("size", DISPATCH_QUEUE_CONCURRENT);
    dispatch_sync(queue, ^{
        size1 = [weakSelf boundingRectWithSize:size options:NSStringDrawingUsesLineFragmentOrigin attributes:attributes context:nil].size;;
    });
    return size1;
}

- (CGSize)boundingRectWithSize:(CGSize)size
                  withTextFont:(UIFont *)font lineSpace:(CGFloat)lineSpace
{
    if ([self isEqualToString:@""]) {
        return CGSizeMake(0, 0);
    }
    NSMutableParagraphStyle *paragraphStyle = [[NSMutableParagraphStyle alloc] init];
    paragraphStyle.lineBreakMode = NSLineBreakByWordWrapping;
    paragraphStyle.lineSpacing = lineSpace;
    NSDictionary *attributes = @{NSFontAttributeName:font, NSParagraphStyleAttributeName:paragraphStyle.copy};
    return [self boundingRectWithSize:size options:NSStringDrawingUsesLineFragmentOrigin attributes:attributes context:nil].size;
}

- (CGSize)boundingRectWithSize:(CGSize)size
                  withTextFont:(UIFont *)font lineSpace:(CGFloat)lineSpace AndheadIndent:(CGFloat)headIndent
{
    if ([self isEqualToString:@""]) {
        return CGSizeMake(0, 0);
    }
    NSMutableParagraphStyle *paragraphStyle = [[NSMutableParagraphStyle alloc] init];
    paragraphStyle.lineBreakMode = NSLineBreakByWordWrapping;
    paragraphStyle.lineSpacing = lineSpace;
    paragraphStyle.firstLineHeadIndent = headIndent;
    NSDictionary *attributes = @{NSFontAttributeName:font, NSParagraphStyleAttributeName:paragraphStyle.copy};
    return [self boundingRectWithSize:size options:NSStringDrawingUsesLineFragmentOrigin attributes:attributes context:nil].size;
}

/**
 *  计算文字宽度
 *
 *  @param font   字体大小
 *  @param height 约束宽度
 */
- (CGFloat)widthWithFont:(UIFont *)font constrainedToHeight:(CGFloat)height
{
    UIFont *textFont = font ? font : [UIFont systemFontOfSize:[UIFont systemFontSize]];
    
    CGSize textSize;
    
#if __IPHONE_OS_VERSION_MIN_REQUIRED < 70000
    if ([self respondsToSelector:@selector(boundingRectWithSize:options:attributes:context:)]) {
        NSMutableParagraphStyle *paragraph = [[NSMutableParagraphStyle alloc] init];
        paragraph.lineBreakMode = NSLineBreakByWordWrapping;
        NSDictionary *attributes = @{NSFontAttributeName: textFont,NSParagraphStyleAttributeName: paragraph};
        textSize = [self boundingRectWithSize:CGSizeMake(CGFLOAT_MAX, height) options:(NSStringDrawingUsesLineFragmentOrigin | NSStringDrawingTruncatesLastVisibleLine) attributes:attributes context:nil].size;
    } else {
        textSize = [self sizeWithFont:textFont constrainedToSize:CGSizeMake(CGFLOAT_MAX, height) lineBreakMode:NSLineBreakByWordWrapping];
    }
#else
    NSMutableParagraphStyle *paragraph = [[NSMutableParagraphStyle alloc] init];
    paragraph.lineBreakMode = NSLineBreakByWordWrapping;
    NSDictionary *attributes = @{NSFontAttributeName: textFont,NSParagraphStyleAttributeName: paragraph};
    textSize = [self boundingRectWithSize:CGSizeMake(CGFLOAT_MAX, height) options:(NSStringDrawingUsesLineFragmentOrigin | NSStringDrawingTruncatesLastVisibleLine) attributes:attributes context:nil].size;
#endif
    return ceil(textSize.width);
}

#pragma mark - 获取返回的样式
+(NSString *)currentTimeAndFormat:(NSString *)format
{
    NSDate * senddate = [NSDate date];
    NSDateFormatter  *dateformatter=[[NSDateFormatter alloc] init];
    [dateformatter setDateFormat:format];
    NSString *  locationString=[dateformatter stringFromDate:senddate];
    return locationString;
}

#pragma mark - 转换格式 str 字符串 yangShi 要求返回格式 moRenYangShi 样式
+(NSString *)ChangZiYouYangShi:(NSString *)str AndYangShi:(NSString *)yangShi AndModelRenYangShi:(NSString *)moRenYangShi
{
    NSDateFormatter *inputFormatter = [[NSDateFormatter alloc] init];
    [inputFormatter setLocale:[[NSLocale alloc] initWithLocaleIdentifier:@"en_US"]];
    [inputFormatter setDateFormat:moRenYangShi];
    NSDate* inputDate = [inputFormatter dateFromString:str];
    
    NSDateFormatter *outputFormatter = [[NSDateFormatter alloc] init];
    [outputFormatter setLocale:[NSLocale currentLocale]];
    [outputFormatter setDateFormat:yangShi];
    NSString *strs = [outputFormatter stringFromDate:inputDate];
    return strs;
}

#pragma mark -比较时间大小
+(int)compareDate:(NSString*)date01 withDate:(NSString*)date02 AndYangShi:(NSString *)yangshi
{
    int ci;
    NSDateFormatter *df = [[NSDateFormatter alloc] init];
    [df setDateFormat:yangshi];
    NSDate *dt1 = [df dateFromString:date01];
    NSDate *dt2 = [df dateFromString:date02];
    NSComparisonResult result = [dt1 compare:dt2];
    switch (result)
    {
            //date02比date01大
        case NSOrderedAscending: ci=1; break;
            //date02比date01小
        case NSOrderedDescending: ci=-1; break;
            //date02=date01
        case NSOrderedSame: ci=0; break;
        default: NSLog(@"erorr dates %@, %@", dt2, dt1); break;
    }
    return ci;
}

#pragma mark - 判断周几 格式yyyyMMdd
+(NSString *)judgeDay:(NSString *)str
{
    NSDateComponents *_comps = [[NSDateComponents alloc] init];
    int days=[[str substringFromIndex:6] intValue];
    int month =[[[str substringToIndex:6] substringFromIndex:4] intValue];
    int year =[[str substringToIndex:4] intValue];
    //    NSLog(@"%d%d%d",year,month,days);
    [_comps setDay:days];
    [_comps setMonth: month];
    [_comps setYear:year];
    NSCalendar *gregorian = [[NSCalendar alloc]
                             initWithCalendarIdentifier:NSCalendarIdentifierGregorian];
    NSDate *_date = [gregorian dateFromComponents:_comps];
    NSDateComponents *weekdayComponents =[gregorian components:NSCalendarUnitWeekday fromDate:_date];
    NSInteger _weekday = [weekdayComponents weekday];
    //    NSLog(@"_weekday::%d",_weekday);
    switch (_weekday) {
        case 1:
            return @"星期天";
            break;
        case 2:
            return @"星期一";
            break;
        case 3:
            return @"星期二";
            break;
        case 4:
            return @"星期三";
            break;
        case 5:
            return @"星期四";
            break;
        case 6:
            return @"星期五";
            break;
        case 7:
            return @"星期六";
            break;
            
        default:
            break;
    }
    return nil;
}

+(NSString *)judgeTodayWeek:(NSDate *)date
{
    NSCalendar *gregorian = [[NSCalendar alloc]
                             initWithCalendarIdentifier:NSCalendarIdentifierGregorian];
    NSDateComponents *weekdayComponents =[gregorian components:NSCalendarUnitWeekday fromDate:date];
    NSInteger _weekday = [weekdayComponents weekday];
    //    NSLog(@"_weekday::%d",_weekday);
    switch (_weekday) {
        case 1:
            return @"日";
            break;
        case 2:
            return @"一";
            break;
        case 3:
            return @"二";
            break;
        case 4:
            return @"三";
            break;
        case 5:
            return @"四";
            break;
        case 6:
            return @"五";
            break;
        case 7:
            return @"六";
            break;
            
        default:
            break;
    }
    return nil;
}

#pragma mark 判断两个日期相差天数
+(NSInteger)getDaysFrom:(NSDate *)serverDate To:(NSDate *)endDate
{
    NSCalendar *gregorian = [[NSCalendar alloc]
                             initWithCalendarIdentifier:NSCalendarIdentifierGregorian];
    [gregorian setFirstWeekday:2];
    //去掉时分秒信息
    NSDate *fromDate;
    NSDate *toDate;
    [gregorian rangeOfUnit:NSCalendarUnitDay startDate:&fromDate interval:NULL forDate:serverDate];
    [gregorian rangeOfUnit:NSCalendarUnitDay startDate:&toDate interval:NULL forDate:endDate];
    NSDateComponents *dayComponents = [gregorian components:NSCalendarUnitDay fromDate:fromDate toDate:toDate options:0];
    return dayComponents.day;
}

#pragma mark - 判断增加时间后的日期
+(NSString *)JudegeAddDay:(NSInteger)addDay
{
    NSDateFormatter *dateFormatter = [NSDateFormatter new];
    [dateFormatter setDateFormat:@"yyyyMMdd"];
    NSDate *myDate = [dateFormatter dateFromString:[self currentYearToDay]];
    NSDate *newDate = [myDate dateByAddingTimeInterval:60 * 60 * 24 * addDay];
     return [dateFormatter stringFromDate:newDate];
}
                      
+(NSString *)currentYearToDay
{
    NSDate * senddate= [NSDate date];
    NSDateFormatter  *dateformatter=[[NSDateFormatter alloc] init];
    [dateformatter setDateFormat:@"YYYYMMdd"];
    NSString *  locationString=[dateformatter stringFromDate:senddate];
    return locationString;
}

#pragma mark -  判断手机号码格式是否正确
+ (BOOL)valiMobile:(NSString *)mobile
{
    mobile = [mobile stringByReplacingOccurrencesOfString:@" " withString:@""];
    if (mobile.length != 11)
    {
        return NO;
    }else{
        /**
         * 移动号段正则表达式
         */
        NSString *CM_NUM = @"^((13[4-9])|(147)|(15[0-2,7-9])|(178)|(18[2-4,7-8]))\\d{8}|(1705)\\d{7}$";
        /**
         * 联通号段正则表达式
         */
        NSString *CU_NUM = @"^((13[0-2])|(145)|(15[5-6])|(176)|(18[5,6]))\\d{8}|(1709)\\d{7}$";
        /**
         * 电信号段正则表达式
         */
        NSString *CT_NUM = @"^((133)|(153)|(177)|(18[0,1,9]))\\d{8}$";
        NSPredicate *pred1 = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", CM_NUM];
        BOOL isMatch1 = [pred1 evaluateWithObject:mobile];
        NSPredicate *pred2 = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", CU_NUM];
        BOOL isMatch2 = [pred2 evaluateWithObject:mobile];
        NSPredicate *pred3 = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", CT_NUM];
        BOOL isMatch3 = [pred3 evaluateWithObject:mobile];

        if (isMatch1 || isMatch2 || isMatch3) {
            return YES;
        }else{
            return NO;
        }
    }
}

#pragma mark - 获取拼音首字母(传入汉字字符串, 返回大写拼音首字母)
+ (NSString *)firstCharactor:(NSString *)aString
{
    //转成了可变字符串
    NSMutableString *str = [NSMutableString stringWithString:aString];
    //先转换为带声调的拼音
    CFStringTransform((CFMutableStringRef)str,NULL, kCFStringTransformMandarinLatin,NO);
    //再转换为不带声调的拼音
    CFStringTransform((CFMutableStringRef)str,NULL, kCFStringTransformStripDiacritics,NO);
    //转化为大写拼音
    NSString *pinYin = [str capitalizedString];
    //获取并返回首字母
    return [pinYin substringToIndex:1];
}

+(instancetype)ArrayWithStr:(NSMutableDictionary *)sortDic
{
    return [[self alloc]JSONStringWithDic:sortDic];
}

-(NSString *)JSONStringWithDic:(NSMutableDictionary *)sortDic
{
    NSMutableArray *sortList = [[NSMutableArray alloc] init];
    
    [sortList addObject:sortDic];
    
    NSData *data = [NSJSONSerialization dataWithJSONObject:sortList options:kNilOptions error:nil];
    
    NSString * str=[[NSString alloc]initWithData:data encoding:NSUTF8StringEncoding];
    
    return str;
}

-(NSString *)JSONStringWithArrDic:(NSMutableDictionary *)dic
{
    NSData *data = [NSJSONSerialization dataWithJSONObject:dic options:kNilOptions error:nil];
    NSString * str=[[NSString alloc]initWithData:data encoding:NSUTF8StringEncoding];
    return str;
}

#pragma mark - 银行卡格式校验
+ (BOOL) checkCardNo:(NSString*) cardNo{

    int oddsum = 0;   //奇数求和
    
    int evensum = 0;  //偶数求和
    
    int allsum = 0;
    
    int cardNoLength = (int)[cardNo length];
    
    int lastNum = [[cardNo substringFromIndex:cardNoLength-1] intValue];
    
    cardNo = [cardNo substringToIndex:cardNoLength - 1];
    
    for (int i = cardNoLength -1 ; i>=1;i--) {
        
        NSString *tmpString = [cardNo substringWithRange:NSMakeRange(i-1, 1)];
        
        int tmpVal = [tmpString intValue];
        
        if (cardNoLength % 2 ==1 ) {
            
            if((i % 2) == 0){
                
                tmpVal *= 2;
                
                if(tmpVal>=10)
                    
                    tmpVal -= 9;
                
                evensum += tmpVal;
                
            }else{
                
                oddsum += tmpVal;
                
            }
            
        }else{
            
            if((i % 2) == 1){
                
                tmpVal *= 2;
                
                if(tmpVal>=10)
                    
                    tmpVal -= 9;
                
                evensum += tmpVal;
            }else{
                
                oddsum += tmpVal;
            }
        }
    }
    
    allsum = oddsum + evensum;
    
    allsum += lastNum;
    
    if((allsum % 10) == 0)
        
        return YES;
    else
        return NO;
}

#pragma mark - 根据时间撮返回时间
+(NSString *)sendTimeStrToSSS:(NSString *)timeStr
{
    NSDateFormatter* formatter = [[NSDateFormatter alloc] init];
    [formatter setDateStyle:NSDateFormatterMediumStyle];
    [formatter setTimeStyle:NSDateFormatterShortStyle];
    [formatter setDateFormat:@"yyyy-MM-dd HH:mm:ss.SSS"];
    NSDate* date = [NSDate dateWithTimeIntervalSince1970:[timeStr doubleValue]];
    NSString *dateString = [formatter stringFromDate:date];
    return dateString;
}

#pragma mark - 是否是合法的支付金额数
+ (BOOL)isCorrectMoneyNumber:(NSString *)moneyNum
{
    NSArray *array = @[@"0",@"1",@"2",@"3",@"4",@"5",@"6",@"7",@"8",@"9"];
    
    int pointCount = 0;
    for (int i = 0; i < moneyNum.length; i++) {
        int count = 0;
        NSString *first = [moneyNum substringWithRange:NSMakeRange(i, 1)];
        NSString *second = @"";
        if ((i + 1) < moneyNum.length) {
            second = [moneyNum substringWithRange:NSMakeRange(i + 1, 1)];
        }
        for (NSString *b in array) {
            if ([first isEqualToString:b] || [first isEqualToString:@"."]) {
                
            }else{
                count++;
            }
            if (count == 10) {
                return NO;
            }
        }
        if ([first isEqualToString:@"."]) {
            pointCount++;
        }
        if (pointCount > 1) {
            return NO;
        }
        if ([first isEqualToString:@"."] && i == 0) {
            return NO;
        }
        if ([first isEqualToString:@"0"] && i == 0 && ![second isEqualToString:@""] && ![second isEqualToString:@"."]) {
            return NO;
        }
        if ([first isEqualToString:@"0"] && i == 0 && !second) {
            return NO;
        }
    }
    return YES;
}

#pragma mark - 车牌号验证
+ (BOOL) checkCarNumber:(NSString *) CarNumber{
    NSString *bankNum = @"^[\u4e00-\u9fa5]{1}[a-zA-Z]{1}[a-zA-Z_0-9]{4}[a-zA-Z_0-9_\u4e00-\u9fa5]$";
    NSPredicate *pred = [NSPredicate predicateWithFormat:@"SELF MATCHES %@",bankNum];
    BOOL isMatch = [pred evaluateWithObject:CarNumber];
    return isMatch;
}

#pragma mark - 正则只能输入数字和字母
+ (BOOL) checkTeshuZifuNumber:(NSString *) CheJiaNumber{
    NSString *bankNum=@"^[A-Za-z0-9]+$";
    NSPredicate *pred = [NSPredicate predicateWithFormat:@"SELF MATCHES %@",bankNum];
    BOOL isMatch = [pred evaluateWithObject:CheJiaNumber];
    return isMatch;
}

#pragma 正则匹配邮箱号
+ (BOOL)checkMailInput:(NSString *)mail{
    
    NSString *emailRegex = @"[A-Z0-9a-z._%+-]+@[A-Za-z0-9.-]+\\.[A-Za-z]{2,4}";
    NSPredicate *emailTest = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", emailRegex];
    return [emailTest evaluateWithObject:mail];
}

+(NSString *)filterHTML:(NSString *)html
{
    NSScanner * scanner = [NSScanner scannerWithString:html];
    NSString * text = nil;
    while([scanner isAtEnd]==NO)
    {
        [scanner scanUpToString:@"<" intoString:nil];
        [scanner scanUpToString:@">" intoString:&text];
        html = [html stringByReplacingOccurrencesOfString:[NSString stringWithFormat:@"%@>",text] withString:@""];
    }
    NSString * returnStr = [html stringByReplacingOccurrencesOfString:@"&nbsp;" withString:@""];
    return returnStr;
}

+ (BOOL)isCorrect:(NSString *)IDNumber
{
    NSMutableArray *IDArray = [NSMutableArray array];
    if (IDNumber.length != 18) {
        return NO;
    }
    // 遍历身份证字符串,存入数组中
    for (int i =0; i < 18; i++) {
        NSRange range =NSMakeRange(i, 1);
        NSString *subString = [IDNumber substringWithRange:range];
        [IDArray addObject:subString];
    }
    // 系数数组
    NSArray *coefficientArray = [NSArray arrayWithObjects:@"7",@"9", @"10",@"5", @"8",@"4", @"2",@"1", @"6",@"3", @"7",@"9", @"10",@"5", @"8",@"4", @"2",nil];
    // 余数数组
    NSArray *remainderArray = [NSArray arrayWithObjects:@"1",
                                   @"0", @"X",
                                   @"9", @"8",
                                   @"7", @"6",
                                   @"5", @"4",
                                   @"3", @"2",
                                   nil];
    // 每一位身份证号码和对应系数相乘之后相加所得的和
    int sum=0;
    for (int i =0; i < 17; i++) {
        int coefficient = [coefficientArray[i] intValue];
        int ID = [IDArray[i] intValue];
        sum += coefficient * ID;
    }
    // 这个和除以11的余数对应的数
    NSString *str = remainderArray[(sum %11)];
    //身份证号码最后一位
    NSString *string = [IDNumber substringFromIndex:17];
    // 如果这个数字和身份证最后一位相同,则符合国家标准,返回YES
    if ([str isEqualToString:string]) {
        return YES;
    } else {
        return NO;
    }
}

@end
